package com.celesea.configuration.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.session.Session;
import org.springframework.session.web.http.HttpSessionStrategy;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HeaderHttpSessionStrategy implements HttpSessionStrategy {

    private static Logger logger = LoggerFactory.getLogger(HeaderHttpSessionStrategy.class);

    private String headerName = "x-security-token";

    @Override
    public String getRequestedSessionId(HttpServletRequest request) {
        logger.info("=======>>>>>>>>>>getRequestedSessionId:{}",request.getHeader(this.headerName));
        return request.getHeader(this.headerName);
    }

    @Override
    public void onNewSession(Session session, HttpServletRequest request,
                             HttpServletResponse response) {
        logger.info("=======>>>>>>>>>>onNewSession:{}",session.getId());
        response.setHeader(this.headerName, session.getId());
    }

    @Override
    public void onInvalidateSession(HttpServletRequest request,
                                    HttpServletResponse response) {
        response.setHeader(this.headerName, "");
    }

    /**
     * The name of the header to obtain the session id from. Default is "x-security-token".
     *
     * @param headerName the name of the header to obtain the session id from.
     */
    public void setHeaderName(String headerName) {
        Assert.notNull(headerName, "headerName cannot be null");
        this.headerName = headerName;
    }
}
